// File: UsersController.java

package ORAjdbcSwing;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.sql.*;


public class UsersController implements ActionListener, ExceptionListener
{
    private MvbView mvb = null;
    private UsersModel Users = null;

    // constants used for describing the outcome of an operation
    public static final int OPERATIONSUCCESS = 0;
    public static final int OPERATIONFAILED = 1;
    public static final int VALIDATIONERROR = 2;

    public UsersController(MvbView mvb)
    {
        this.mvb = mvb;
        Users = new UsersModel();

        // register to receive exception events from Users
        Users.addExceptionListener(this);
    }


    /*
     * This event handler gets called when the user makes a menu
     * item selection.
     */
    public void actionPerformed(ActionEvent e)
    {
        String actionCommand = e.getActionCommand();

        // you cannot use == for string comparisons
        if (actionCommand.equals("Insert Users"))
        {
            UsersInsertDialog iDialog = new UsersInsertDialog(mvb);
            iDialog.pack();
            mvb.centerWindow(iDialog);
            iDialog.setVisible(true);
            return;
        }

        if (actionCommand.equals("Update Users"))
        {
            UsersUpdateDialog uDialog = new UsersUpdateDialog(mvb);
            uDialog.pack();
            mvb.centerWindow(uDialog);
            uDialog.setVisible(true);
            return;
        }

        if (actionCommand.equals("Delete Users"))
        {
            UsersDeleteDialog dDialog = new UsersDeleteDialog(mvb);
            dDialog.pack();
            mvb.centerWindow(dDialog);
            dDialog.setVisible(true);
            return;
        }

        if (actionCommand.equals("Show Users"))
        {
            showAllUsers();
            return;
        }

        if (actionCommand.equals("Edit Users"))
        {
            editAllUsers();
            return;
        }
    }



    /*
     * This event handler gets called when an exception event
     * is generated. It displays the exception message on the status
     * text area of the main GUI.
     */
    public void exceptionGenerated(ExceptionEvent ex)
    {
        String message = ex.getMessage();

        // annoying beep sound
        Toolkit.getDefaultToolkit().beep();

        if (message != null)
        {
            mvb.updateStatusBar(ex.getMessage());
        }
        else
        {
            mvb.updateStatusBar("An exception occurred!");
        }
    }


    /*
     * This method displays all branches in a non-editable JTable
     */
    private void showAllUsers()
    {
        ResultSet rs = Users.showusers();

        // CustomTableModel maintains the result set's data, e.g., if
        // the result set is updatable, it will update the database
        // when the table's data is modified.
        CustomTableModel model = new CustomTableModel(Users.getConnection(), rs);
        CustomTable data = new CustomTable(model);

        // register to be notified of any exceptions that occur in the model and table
        model.addExceptionListener(this);
        data.addExceptionListener(this);

        // Adds the table to the scrollpane.
        // By default, a JTable does not have scroll bars.
        mvb.addTable(data);
    }


    /*
     * This method displays all branches in an editable JTable
     */
    private void editAllUsers()
    {
        ResultSet rs = Users.editBranch();

        CustomTableModel model = new CustomTableModel(Users.getConnection(), rs);
        CustomTable data = new CustomTable(model);

        model.addExceptionListener(this);
        data.addExceptionListener(this);

        mvb.addTable(data);
    }


    /*
     * This class creates a dialog box for inserting a Users.
     */
    class UsersInsertDialog extends JDialog implements ActionListener
    {
       // private JTextField userID = new JTextField(4);
         private JTextField userID = new JTextField(4);
       // private JTextField userIP = new JTextField(10);
         private JTextField userIP = new JTextField(10);
        private JTextField userfirstname = new JTextField(15);
        private JTextField userlastname = new JTextField(10);
        private JTextField alias = new JTextField(10);


        /*
         * Constructor. Creates the dialog's GUI.
         */
        public UsersInsertDialog(JFrame parent)
        {
            super(parent, "Insert Users", true);
            setResizable(false);

            JPanel contentPane = new JPanel(new BorderLayout());
            setContentPane(contentPane);
            contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

            // this panel will contain the text field labels and the text fields.
            JPanel inputPane = new JPanel();
            inputPane.setBorder(BorderFactory.createCompoundBorder(
                         new TitledBorder(new EtchedBorder(), "Users Fields"),
                         new EmptyBorder(5, 5, 5, 5)));

            // add the text field labels and text fields to inputPane
            // using the GridBag layout manager

            GridBagLayout gb = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            inputPane.setLayout(gb);

            // create and place Users id label
            JLabel label= new JLabel("UsersID: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(0, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);


            // place Users id field
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(0, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(userID, c);
            inputPane.add(userID);

            // create and place Users name label
            label = new JLabel("UserFirsName: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(5, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);

            // place Users name field
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(5, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(userIP, c);
            inputPane.add(userIP);

            // create and place Users address label
            label = new JLabel("UserLastName: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(5, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);

            // place Users address field
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(5, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(userfirstname, c);
            inputPane.add(userfirstname);

            // create and place Users city label
            label = new JLabel("Alias: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(5, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);

            // place Users city field
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(5, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(userlastname, c);
            inputPane.add(userlastname);

            // create and place Users phone label
            label = new JLabel("UserIp: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(5, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);

            // place Users phone field
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(5, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(alias, c);
            inputPane.add(alias);

            // when the return key is pressed in the last field
            // of this form, the action performed by the ok button
            // is executed
            alias.addActionListener(this);
            alias.setActionCommand("OK");

            // panel for the OK and cancel buttons
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
            buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));

            JButton OKButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            OKButton.addActionListener(this);
            OKButton.setActionCommand("OK");
            cancelButton.addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e)
                    {
                        dispose();
                    }
                });

            // add the buttons to buttonPane
            buttonPane.add(Box.createHorizontalGlue());
            buttonPane.add(OKButton);
            buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
            buttonPane.add(cancelButton);

            contentPane.add(inputPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);

            addWindowListener(new WindowAdapter()
                {
                    public void windowClosing(WindowEvent e)
                    {
                        dispose();
                    }
                });
        }


        /*
         * Event handler for the OK button in UsersInsertDialog
         */
        public void actionPerformed(ActionEvent e)
        {
            String actionCommand = e.getActionCommand();

            if (actionCommand.equals("OK"))
            {
                if (validateInsert() != VALIDATIONERROR)
                {
                    dispose();
                }
                else
                {
                    Toolkit.getDefaultToolkit().beep();

                    // display a popup to inform the user of the validation error
                    JOptionPane errorPopup = new JOptionPane();
                    errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }


        /*
         * Validates the text fields in UsersInsertDialog and then
         * calls Users.insertBranch() if the fields are valid.
         * Returns the operation status, which is one of OPERATIONSUCCESS,
         * OPERATIONFAILED, VALIDATIONERROR.
         */
        private int validateInsert()
        {
            try
            {
                Integer uid;
                String ufirstname;
                String ulastname;
                String ualias;
                Integer uip;

                if (userID.getText().trim().length() != 0)
                {
                    uid = Integer.valueOf(userID.getText().trim());

                    // check for duplicates
                    if (Users.findusers(uid.intValue()))
                    {
                        Toolkit.getDefaultToolkit().beep();
                        mvb.updateStatusBar("Users" + uid.toString() + " already exists!");
                        return OPERATIONFAILED;
                    }
                }
                else
                {
                    return VALIDATIONERROR;
                }

                if (userIP.getText().trim().length() != 0)
                {
                    ufirstname = userIP.getText().trim();
                }
                else
                {
                    return VALIDATIONERROR;
                }

                if (userfirstname.getText().trim().length() != 0)
                {
                    ulastname = userfirstname.getText().trim();
                }
                else
                {
                    ulastname = null;
                }

                if (userlastname.getText().trim().length() != 0)
                {
                    ualias = userlastname.getText().trim();
                }
                else
                {
                    return VALIDATIONERROR;
                }

                if (alias.getText().trim().length() != 0)
                {
                    uip = Integer.valueOf(alias.getText().trim());
                }
                else
                {
                    uip = null;
                }


                mvb.updateStatusBar("Inserting Users...");

                if (Users.insertUsers(uid, ufirstname, ulastname, ualias, uip))
                {
                    mvb.updateStatusBar("Operation successful.");
                    showAllUsers();
                    return OPERATIONSUCCESS;
                }
                else
                {
                    Toolkit.getDefaultToolkit().beep();
                    mvb.updateStatusBar("Operation failed.");
                    return OPERATIONFAILED;
                }
            }
            catch (NumberFormatException ex)
            {
                // this exception is thrown when a string
                // cannot be converted to a number
                return VALIDATIONERROR;
            }
        }
    }


    /*
     * This class creates a dialog box for updating a Users.
     */
    class UsersUpdateDialog extends JDialog implements ActionListener
    {
        private JTextField branchID = new JTextField(4);
        private JTextField UsersName = new JTextField(10);


        /*
         * Constructor. Creates the dialog's GUI.
         */
        public UsersUpdateDialog(JFrame parent)
        {
            super(parent, "Update Branch", true);
            setResizable(false);

            JPanel contentPane = new JPanel(new BorderLayout());
            setContentPane(contentPane);
            contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

            // this panel contains the text field labels and
            // the text fields.
            JPanel inputPane = new JPanel();
            inputPane.setBorder(BorderFactory.createCompoundBorder(
                         new TitledBorder(new EtchedBorder(), "Branch Fields"),
                         new EmptyBorder(5, 5, 5, 5)));

            // add the text field labels and text fields to inputPane
            // using the GridBag layout manager

            GridBagLayout gb = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            inputPane.setLayout(gb);

            // create and place Users id label
            JLabel label= new JLabel("Branch ID: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(0, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);

            // place Users id field
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(0, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(branchID, c);
            inputPane.add(branchID);

            // create and place Users name label
            label = new JLabel("New Branch Name: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(5, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);

            // place Users name field
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(5, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(UsersName, c);
            inputPane.add(UsersName);

            // when the return key is pressed in the last field
            // of this form, the action performed by the ok button
            // is executed
            UsersName.addActionListener(this);
            UsersName.setActionCommand("OK");

            // panel for the OK and cancel buttons
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
            buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));

            JButton OKButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            OKButton.addActionListener(this);
            OKButton.setActionCommand("OK");
            cancelButton.addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e)
                    {
                        dispose();
                    }
                });

            // add buttons to buttonPane
            buttonPane.add(Box.createHorizontalGlue());
            buttonPane.add(OKButton);
            buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
            buttonPane.add(cancelButton);

            contentPane.add(inputPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);

            addWindowListener(new WindowAdapter()
                {
                    public void windowClosing(WindowEvent e)
                    {
                        dispose();
                    }
                });
        }


        /*
         * Event handler for the OK button in UsersUpdateDialog
         */
        public void actionPerformed(ActionEvent e)
        {
            String actionCommand = e.getActionCommand();

            if (actionCommand.equals("OK"))
            {
                if (validateUpdate() != VALIDATIONERROR)
                {
                    dispose();
                }
                else
                {
                    Toolkit.getDefaultToolkit().beep();

                    // display a popup to inform the user of the error
                    JOptionPane errorPopup = new JOptionPane();
                    errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }


        /*
         * Validates the text fields in UsersUpdateDialog and then
         * calls Users.branchUpdate() if the fields are valid.
         * Returns the operation status.
         */
        private int validateUpdate()
        {
            try
            {
                int bid;
                String bname;

                if (branchID.getText().trim().length() != 0)
                {
                    bid = Integer.valueOf(branchID.getText().trim()).intValue();

                    // check if Users exists
                    if (!Users.findusers(bid))
                    {
                        Toolkit.getDefaultToolkit().beep();
                        mvb.updateStatusBar("Branch " + bid + " does not exist!");
                        return OPERATIONFAILED;
                    }
                }
                else
                {
                    return VALIDATIONERROR;
                }

                if (UsersName.getText().trim().length() != 0)
                {
                    bname = UsersName.getText().trim();
                }
                else
                {
                    return VALIDATIONERROR;
                }

                mvb.updateStatusBar("Updating Users...");

                if (Users.updateUsers(bid, bname))
                {
                    mvb.updateStatusBar("Operation successful.");
                    showAllUsers();
                    return OPERATIONSUCCESS;
                }
                else
                {
                    Toolkit.getDefaultToolkit().beep();
                    mvb.updateStatusBar("Operation failed.");
                    return OPERATIONFAILED;
                }
            }
            catch (NumberFormatException ex)
            {
                return VALIDATIONERROR;
            }
        }
    }



    /*
     * This class creates a dialog box for deleting a Users.
     */
    class UsersDeleteDialog extends JDialog implements ActionListener
    {
        private JTextField branchID = new JTextField(4);


        /*
         * Constructor. Creates the dialog's GUI.
         */
        public UsersDeleteDialog(JFrame parent)
        {
            super(parent, "Delete Users", true);
            setResizable(false);

            JPanel contentPane = new JPanel(new BorderLayout());
            setContentPane(contentPane);
            contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

            // this panel contains the text field labels and the text fields.
            JPanel inputPane = new JPanel();
            inputPane.setBorder(BorderFactory.createCompoundBorder(
                         new TitledBorder(new EtchedBorder(), "Branch Fields"),
                         new EmptyBorder(5, 5, 5, 5)));

            // add the text field labels and text fields to inputPane
            // using the GridBag layout manager

            GridBagLayout gb = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            inputPane.setLayout(gb);

            // create and place Users id label
            JLabel label= new JLabel("Branch ID: ", SwingConstants.RIGHT);
            c.gridwidth = GridBagConstraints.RELATIVE;
            c.insets = new Insets(0, 0, 0, 5);
            c.anchor = GridBagConstraints.EAST;
            gb.setConstraints(label, c);
            inputPane.add(label);

            // place Users id field
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(0, 0, 0, 0);
            c.anchor = GridBagConstraints.WEST;
            gb.setConstraints(branchID, c);
            inputPane.add(branchID);

            // when the return key is pressed while in the
            // userID field, the action performed by the ok button
            // is executed
            branchID.addActionListener(this);
            branchID.setActionCommand("OK");

            // panel for the OK and cancel buttons
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
            buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));

            JButton OKButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            OKButton.addActionListener(this);
            OKButton.setActionCommand("OK");
            cancelButton.addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e)
                    {
                        dispose();
                    }
                });

            // add buttons to buttonPane
            buttonPane.add(Box.createHorizontalGlue());
            buttonPane.add(OKButton);
            buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
            buttonPane.add(cancelButton);

            contentPane.add(inputPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);

            addWindowListener(new WindowAdapter()
                {
                    public void windowClosing(WindowEvent e)
                    {
                        dispose();
                    }
                });
        }


        /*
         * Event handler for the OK button in BranchDeleteDialog
         */
        public void actionPerformed(ActionEvent e)
        {
            String actionCommand = e.getActionCommand();

            if (actionCommand.equals("OK"))
            {
                if (validateDelete() != VALIDATIONERROR)
                {
                    dispose();
                }
                else
                {
                    Toolkit.getDefaultToolkit().beep();

                    // display a popup to inform the user of the error
                    JOptionPane errorPopup = new JOptionPane();
                    errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }


        /*
         * Validates the text fields in BranchDeleteDialog and then
         * calls Users.branchDelete() if the fields are valid.
         * Returns the operation status.
         */
        private int validateDelete()
        {
            try
            {
                int bid;

                if (branchID.getText().trim().length() != 0)
                {
                    bid = Integer.valueOf(branchID.getText().trim()).intValue();

                    // check if Users exists
                    if (!Users.findusers(bid))
                    {
                        Toolkit.getDefaultToolkit().beep();
                        mvb.updateStatusBar("Branch " + bid + " does not exist!");
                        return OPERATIONFAILED;
                    }
                }
                else
                {
                    return VALIDATIONERROR;
                }

                mvb.updateStatusBar("Deleting branch...");

                if (Users.deleteusers(bid))
                {
                    mvb.updateStatusBar("Operation successful.");
                    showAllUsers();
                    return OPERATIONSUCCESS;
                }
                else
                {
                    Toolkit.getDefaultToolkit().beep();
                    mvb.updateStatusBar("Operation failed.");
                    return OPERATIONFAILED;
                }
            }
            catch (NumberFormatException ex)
            {
                return VALIDATIONERROR;
            }
        }
    }
}

